package post

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteForumPostFavoriteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteForumPostFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteForumPostFavoriteLogic {
	return &DeleteForumPostFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteForumPostFavoriteLogic) DeleteForumPostFavorite(
	req *types.DeleteForumPostFavoriteReq,
	headers *[]*types.Header,
) (*types.BaseMsgResp, error) {
	if (req.PostId == nil || *req.PostId == 0) && (req.PostIds == nil || len(strings.TrimSpace(*req.PostIds)) == 0) {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_CONTENT_ID_INVALID)
	}

	if req.Type == nil || *req.Type == 0 {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_TYPE_INVALID)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	var ids []uint64
	idMap := make(map[int64]struct{})
	if req.PostIds != nil && len(strings.TrimSpace(*req.PostIds)) > 0 {
		entryIds := strings.Split(strings.TrimSpace(*req.PostIds), ",")
		for _, id := range entryIds {
			if i, err := strconv.ParseInt(id, 10, 64); err == nil && i > 0 {
				if _, ok := idMap[i]; !ok {
					idMap[i] = struct{}{}
					ids = append(ids, uint64(i))
				}
			}
		}
	} else {
		ids = append(ids, *req.PostId)
	}

	reactionType := util.GetForumReactionType(*req.Type)

	for _, id := range ids {
		_, err := l.svcCtx.ForumRpc.LogReaction(l.ctx, &forumclient.LogReactionReq{
			PostId: pointy.GetPointer(id),
			UserId: userId,
			Type:   reactionType,
			Status: uint32(globalkey.StatusDisabled),
		})
		if err != nil {
			return nil, err
		}
	}

	return &types.BaseMsgResp{
		Msg: "操作成功",
	}, nil
}
